from django.views.generic import View
from apps.BaseView import BaseView
from django.shortcuts import render
from apps.Movie.models import Movies, MovieGenre, Ratings
from apps.Index.models import Users
from django.core.paginator import Paginator
from django.http import JsonResponse
import time


class addview(BaseView):

    def get(self, request):
        movieGenres = MovieGenre.objects.all()
        context = {
            'movieGenres': movieGenres,
        }
        return render(request, 'Movie/movie_add.html', context)

    def post(self, request):
        movie = Movies()
        movie.title = request.POST.get('movie.title')
        movie.genres = MovieGenre.objects.get(movieGenresId=int(request.POST.get('movie.genres'))).movieGenresName
        movie.movieDesc = request.POST.get('movie.movieDesc')
        movie.movieYear = request.POST.get('movie.movieYear')
        movie.save()
        context = {'success': True, 'message': '保存成功'}
        return render(request, 'message.html', context)


class deleteview(BaseView):
    def get(self, request):
        return self.handle(request)

    def post(self, request):
        return self.handle(request)

    def handle(self, request):
        movieIds = self.getStrParam(request, 'movieIds')
        movieIds = movieIds.split(',')
        count = 0
        try:
            for movieId in movieIds:
                Movies.objects.get(movieId=movieId).delete()
                count = count + 1
            message = '%s条记录删除成功！' % count
            success = True
        except Exception as e:
            message = '数据库删除发生错误！'
            success = False
        return JsonResponse({"success": success, "message": message})


class updateview(BaseView):
    def get(self, request, movieId):
        movie = Movies.objects.get(movieId=movieId)
        return JsonResponse(movie.getJsonObj())

    def post(self, request, movieId):
        movie = Movies.objects.get(movieId=int(movieId))
        movie.title = request.POST.get('movie.title')
        movie.genres = request.POST.get('movie.genres')
        movie.movieYear = request.POST.get('movie.movieYear')
        movie.movieDesc = request.POST.get('movie.movieDesc')
        movie.save()
        return JsonResponse({'success': True, 'message': '保存成功'})


class ratingview(BaseView):
    def get(self, request, movieId):
        movie = Movies.objects.get(movieId=movieId)
        return JsonResponse(movie.getJsonObj())

    def post(self, request, movieId):
        try:
            rate = Ratings()
            phone = request.session['phone']
            user = Users.objects.get(phone=phone).userId
            rate.movieId = Movies.objects.get(movieId=movieId)
            rate.userId = Users.objects.get(userId=user)
            rate.rating = request.POST.get('movie.rating')
            rate.timestamp = str(time.time())[:10]
            rate.save()
            print(rate.timestamp)
        except:
            print('error')
        return JsonResponse({'success': True, 'message': '保存成功！'})


class listview(BaseView):
    def get(self, request):
        return render(request, 'Movie/movie_query_result.html')

    def post(self, request):
        self.getPageAndSize(request)
        title = self.getStrParam(request, 'title')
        genres = self.getStrParam(request, 'genres')
        movieYear = self.getStrParam(request, 'movieYear')
        movies = Movies.objects.all()
        if title != '':
            movies = movies.filter(title__contains=title)
        if genres != '':
            movies = movies.filter(genres__contains=genres)
        if movieYear != '':
            movies = movies.filter(movieYear__contains=movieYear)
        movies = movies.order_by('movieId')
        self.paginator = Paginator(movies, self.pageSize)
        self.calculatePages()
        movies_page = self.paginator.page(self.currentPage)
        movieList = []
        for movie in movies_page:
            movie = movie.getJsonObj()
            movieList.append(movie)
        movie_res = {
            'rows': movieList,
            'total': self.recordNumber,
        }
        return JsonResponse(movie_res, json_dumps_params={'ensure_ascii': False})


class genreview(View):
    def get(self, request):
        movieGenres = MovieGenre.objects.all()
        movieGenreList = []
        for movieGenre in movieGenres:
            moviegenre = {
                'movieGenresId': movieGenre.movieGenresId,
                'movieGenresName': movieGenre.movieGenresName,
            }
            movieGenreList.append(moviegenre)
        return JsonResponse(movieGenreList, safe=False)
